package org.example.dynamic.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("file_upload")
public class FileUploadController {

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) throws IOException {

        // 生成唯一文件名（避免重复）
        String fileName = new Date().getTime() + "_" +
                UUID.randomUUID().toString() +
                file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        // 保存文件到服务器本地目录（如：/upload/images）
        String uploadDir = "upload/images/";
        File targetDir = new File(uploadDir);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        Path filePath = Paths.get(uploadDir + fileName);
        Files.write(filePath, file.getBytes());

        // 生成访问URL
        String serverUrl = request.getScheme() + "://" +
                request.getServerName() + ":" +
                request.getServerPort() + "/images/" + fileName;

        return ResponseEntity.ok(serverUrl); // 返回可访问的URL
    }
}
